<?php
/**
 * 后台基类控制器
 * @Author 聂哥<376927050@qq.com>
 * @Date: 2022-10-12 19:27:48
*/
namespace app\admin\controller\system;

use app\admin\model\system\SystemRole;
use app\admin\model\system\SystemUser;
use app\admin\service\MenuService;
use think\Controller;

class Base extends Controller
{
    protected function initialize()
    {
        // 验证用户是否登录
        $adminModel = new SystemUser();
        if (($admin = $adminModel->isLogin()) == false) {
            return $this->error('请先正常登录系统','/login');
        }
        // // 检测用户操作权限
        $menu = MenuService::getInfo();
        if( $menu == false ){
            $this->error('菜单不存在或已经被禁用');
        }
        if( $this->checkActionAuth($menu['id']) == false ){
            return $this->redirect('system.admin/noright');
            exit;
        }
        // 获取当前用户信息
        $this->assign('userInfo',$admin);
        $method = $this->request->action();
        $this->assign('method',$method);
        if( $method == 'add' ){
            $this->assign('formData',[]);
        }
    }

    /**
     * 检测是否可以访问
     */
    protected function checkActionAuth($id)
    {
        //超级管理员跳过
        $role_ids = session('admin.role_ids'); 
        $uid = session('admin.id'); 
        if (in_array(SystemRole::SUPER_ADMIN,$role_ids)){
            return true;
        }
        $menuList = session("role_menu_{$uid}");
        if( empty($menuList) ){
            $menuList = MenuService::getSystemMenuIdsByRole($role_ids);
            session("role_menu_{$uid}",$menuList);
        }
        return in_array($id,$menuList);
    }
}